<?php

class Thumb{
    private $img_addr;         //图片文件目录 + 后缀
    private $path;             //目录名
    private $name;             //文件名(没后缀)
    private $width;            //缩略图宽
    private $height;           //缩略图高
    private $suffix;           //后缀名
    private $w;                //原图像宽
    private $h;                //原图像高
    private static $getInstance;

    private function __construct($conf){
        $this->init($conf);
        $this->getImgInfo();
    }

    private function init($conf){
        $this->img_addr = empty($conf['img_addr']) ? '' : $conf['img_addr'];
        $this->path = empty($conf['path']) ? '' : $conf['path'];
        $this->name = empty($conf['name']) ? '' : $conf['name'];
        $this->width = empty($conf['width']) ? '' : $conf['width'];
        $this->height = empty($conf['height']) ? '' : $conf['height'];
    }

    private function __clone(){

    }

    static function getInstance($conf){
        if(!self::$getInstance instanceof self){
            return self::$getInstance = new self($conf);
        }
        return self::$getInstance;
    }

    private function getImgInfo(){
        list($this->w, $this->h, $type) = getimagesize($this->img_addr);

        $type_arr = [1 => 'gif', 2 => 'jpeg', 3 => 'png']; //获得后缀

        $this->suffix = $type_arr[$type];
    }

   function download(){
        $desc_str = 'imagecreatefrom' . $this->suffix;

        $desc_img = $desc_str($this->img_addr); //创建一个新图像

        $true_img = imagecreatetruecolor($this->width, $this->height);

        imagecopyresized($true_img, $desc_img, 0, 0, 0, 0, $this->width, $this->height, $this->w, $this->h);

        // ob_clean(); //清除header前的输出
        //header("Content-Type:image/{$type_arr[$type]}");

        $show_str = 'image' . $this->suffix;

        $new_path = $this->path . '/thumb'; //缩略图存放路径
        if ($this->name != '') {
            if (!is_dir($new_path)) {
                mkdir($new_path);
            }
            $thumb_name = 'thumb_' . $this->name;
            $show_str($true_img, $new_path . '/' . $thumb_name);
            return $new_path . '/' . $thumb_name;
        } else {
            $show_str($true_img);
        }

        imagedestroy($true_img);

   }
}

